/*
 * 	Flan.Zeng 2011-2016	http://git.oschina.net/signup?inviter=flan
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.flan.study.java.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * NIO客户端
 * @author flan
 * @date   2015年12月11日
 */
public class NIOClient {
	
	private Selector selector;
	
	/**
	 * 获得一个Socket通道，并对该通道做一些初始化的工作 
	 * @param ip		服务器IP地址
	 * @param port		服务器端口号
	 * @throws IOException
	 */
	public void initClient(String ip,int port) throws IOException{
		
		// 获得一个Socket通道 
		SocketChannel channel = SocketChannel.open();
		// 设置通道为非阻塞
		channel.configureBlocking(false);
		// 获得一个通道管理器
		selector = Selector.open();
		
		// 客户端连接服务器,其实方法执行并没有实现连接，需要在listen（）方法中调  
        //用channel.finishConnect();才能完成连接
		channel.connect(new InetSocketAddress(ip, port));
		//将通道管理器和该通道绑定，并为该通道注册SelectionKey.OP_CONNECT事件。
		channel.register(selector, SelectionKey.OP_CONNECT);
	}
	
	/**
	 * 采用轮询的方式监听selector上是否有需要处理的事件，如果有，则进行处理
	 * @throws IOException
	 */
	public void listen() throws IOException{
		while(true){
			
			selector.select();
			Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
			
			while(iterator.hasNext()){
				SelectionKey key = (SelectionKey) iterator.next();
				
				iterator.remove();	// 删除已选的key,以防重复处理
				
				if(key.isConnectable()){	// 连接事件发生
					
					SocketChannel channel = (SocketChannel) key.channel();
					
					// 如果正在连接，则完成连接
					if(channel.isConnectionPending()){
						channel.finishConnect();
					}
					
					channel.configureBlocking(false);
					channel.write(ByteBuffer.wrap("你好，我是客户端，请求连接...".getBytes()));
					
					//在和服务端连接成功之后，为了可以接收到服务端的信息，需要给通道设置读的权限。
					channel.register(selector, SelectionKey.OP_READ);
				} else if(key.isReadable()){
					read(key);
				}
			}
			
		}
	}
	
	/**
	 * 处理读取服务端发来的信息 的事件 
	 * @param key
	 * @throws IOException
	 */
	public void read(SelectionKey key) throws IOException{
		// 服务器可读取消息:得到事件发生的Socket通道
		SocketChannel channel = (SocketChannel) key.channel();
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		channel.read(buffer);
		
		String msg = new String(buffer.array());
		System.out.println("客户端 ："+msg);
	}
	
	public static void main(String[] args) throws IOException {
		NIOClient client = new NIOClient();
		client.initClient("127.0.0.1", 8888);
		client.listen();
	}
	
}
